import type { Directive } from "vue";

const map = new WeakMap<Element, { animation: Animation }>();

const observer = new IntersectionObserver(
	entries => {
		entries.forEach(entry => {
			if (!entry.isIntersecting) {
				return;
			}

			const ob = map.get(entry.target);
			if (!ob) {
				return;
			}

			ob.animation.play();
			observer.unobserve(entry.target);
			map.delete(entry.target);
		});
	},
	{
		threshold: 0.1
	}
);

export const vSlideIn: Directive = {
	mounted(el: HTMLElement, binding) {
		const time = (Number(binding.value) || 1) * 1000;
		const animation = el.animate(
			[
				{
					transform: "translateY(80px)",
					opacity: 0
				},
				{
					transform: "translateY(0)",
					opacity: 1
				}
			],
			{
				duration: time,
				fill: "forwards",
				easing: "ease"
			}
		);
		map.set(el, { animation });
		animation.pause();
		observer.observe(el);
	},

	unmounted(el) {
		observer.unobserve(el);
		map.delete(el);
	}
};
